import 'package:flutter/material.dart';
import '../models/picker_models.dart';
import '../utils/localization_util.dart';
import '../widgets/pickers/edit_date_picker.dart';
import '../widgets/pickers/edit_time_picker.dart';
import '../widgets/pickers/filter_date_picker.dart';

/// 日期选择器的浮层UI和状态管理
class PickerOverlay extends StatefulWidget {
  final PickerMode mode;
  final DateTime initialDateTime;
  final DateTime? startTime;
  final FilterType filterType;
  final int yearsBack;
  final String? title;
  final WeekItemBuilder? weekItemBuilder;
  final Locale locale;
  final bool showLaterTime;
  final Function(dynamic) onChange;
  final Function(dynamic) onConfirm;
  final Function() onCancel;

  const PickerOverlay({
    super.key,
    required this.mode,
    required this.initialDateTime,
    required this.onChange,
    required this.onConfirm,
    required this.onCancel,
    required this.showLaterTime,
    required this.locale,
    this.title,
    this.weekItemBuilder,
    this.startTime,
    this.filterType = FilterType.week,
    this.yearsBack = 3,
  });

  // [NEW] 将 show 方法移到这里，更好地封装实现细节
  static void show({
    required BuildContext context,
    required PickerMode mode,
    required Function(dynamic) onConfirm,
    required Locale locale,
    String? title,
    WeekItemBuilder? weekItemBuilder,
    FilterType? filterType,
    DateTime? initialDateTime,
    DateTime? startTime,
    int? yearsBack,
    bool? showLaterTime,
    Function(dynamic)? onChange,
    Function()? onCancel,
  }) {
    OverlayState overlayState = Overlay.of(context);
    late OverlayEntry overlayEntry;

    // 定义一个通用的关闭方法
    void closeOverlay() {
      overlayEntry.remove();
    }

    overlayEntry = OverlayEntry(
      builder: (context) {
        return Material(
          color: Colors.transparent,
          child: PickerOverlay(
            mode: mode,
            title: title,
            weekItemBuilder: weekItemBuilder,
            initialDateTime: initialDateTime ?? DateTime.now(),
            onChange: onChange ?? (_) {},
            filterType: filterType ?? FilterType.week,
            yearsBack: yearsBack ?? 3,
            startTime: startTime,
            showLaterTime: showLaterTime ?? true,
            locale: locale,
            onConfirm: (selectedTime) {
              onConfirm(selectedTime);
              closeOverlay();
            },
            onCancel: () {
              onCancel?.call();
              closeOverlay();
            },
          ),
        );
      },
    );
    overlayState.insert(overlayEntry);
  }

  @override
  State<PickerOverlay> createState() => _PickerOverlayState();
}

class _PickerOverlayState extends State<PickerOverlay> {
  late DateTime _selectedDateTime;
  late dynamic _selectionResult;
  late final PickerLocalizations l10n; // 国际化工具函数
  @override
  void initState() {
    super.initState();
    l10n = PickerLocalizations(widget.locale);
    _selectedDateTime = widget.initialDateTime;
    _initializeSelectionResult();
  }

  void _initializeSelectionResult() {
    switch (widget.mode) {
      case PickerMode.filterDate:
        if (widget.filterType == FilterType.year) {
          _selectionResult = {"year": _selectedDateTime.year};
        } else if (widget.filterType == FilterType.month) {
          _selectionResult = {
            "year": _selectedDateTime.year,
            "month": _selectedDateTime.month
          };
        } else {
          _selectionResult = {
            "startTime": _selectedDateTime,
            "endTime": _selectedDateTime,
          };
        }
        break;
      case PickerMode.editTime:
        _selectionResult = {
          "hour": _selectedDateTime.hour,
          "minute": _selectedDateTime.minute
        };
        break;
      default:
        _selectionResult = _selectedDateTime;
        break;
    }
  }

  void _onValueChanged(dynamic value) {
    setState(() {
      if (value is DateTime) {
        _selectedDateTime = value;
      }
      _selectionResult = value;
    });
    widget.onChange(value);
  }

  void _onConfirm() {
    widget.onConfirm(_selectionResult);
  }

  String _getPickerTitle() {
    if (widget.title != null) return widget.title!;
    switch (widget.mode) {
      case PickerMode.editDate:
        return l10n.editDateTitle;
      case PickerMode.filterDate:
        return l10n.filterDateTitle;
      case PickerMode.editTime:
        return l10n.editTimeTitle;
      case PickerMode.startTime:
        return l10n.startTimeTitle;
      case PickerMode.endTime:
        return l10n.endTimeTitle;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned.fill(
          child: GestureDetector(
            onTap: widget.onCancel,
            child: Container(color: Colors.black54),
          ),
        ),
        Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          child: SafeArea(
            child: Container(
              padding: const EdgeInsets.all(24.0),
              margin:
              const EdgeInsets.symmetric(horizontal: 12.0, vertical: 10.0),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(32),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(bottom: 24),
                    child: Text(
                      _getPickerTitle(),
                      style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: Colors.black),
                    ),
                  ),
                  _buildPickerContent(),
                  const SizedBox(height: 16),
                  _buildActionButtons(),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildPickerContent() {
    switch (widget.mode) {
      case PickerMode.editDate:
        return EditDatePicker(
          initialDate: _selectedDateTime,
          showLaterTime: widget.showLaterTime,
          showMoment: true,
          onDateChanged: _onValueChanged,
          locale: widget.locale,
        );
      case PickerMode.startTime:
        return EditDatePicker(
          initialDate: _selectedDateTime,
          showLaterTime: widget.showLaterTime,
          showMoment: false,
          onDateChanged: _onValueChanged,
          locale: widget.locale,
        );
      case PickerMode.endTime:
        return EditDatePicker(
          initialDate: _selectedDateTime,
          showLaterTime: widget.showLaterTime,
          startTime: widget.startTime,
          showMoment: false,
          onDateChanged: _onValueChanged,
          locale: widget.locale,
        );
      case PickerMode.filterDate:
        return FilterDatePicker(
          type: widget.filterType,
          initialDate: _selectedDateTime,
          yearsBack: widget.yearsBack,
          showLaterTime: widget.showLaterTime,
          onDateChanged: _onValueChanged,
          weekItemBuilder: widget.weekItemBuilder,
          locale: widget.locale,

        );
      case PickerMode.editTime:
        return EditTimePicker(
          initialDate: _selectedDateTime,
          showLaterTime: widget.showLaterTime,
          onDateChanged: _onValueChanged,
          locale: widget.locale,
        );
    }
  }

  Widget _buildActionButtons() {
    return Row(
      children: [
        Expanded(
          child: TextButton(
            style: TextButton.styleFrom(
              backgroundColor: const Color(0XFFF0F0F0),
              padding: const EdgeInsets.symmetric(vertical: 14),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16)),
            ),
            onPressed: widget.onCancel,
            child: Text(l10n.cancel,
                style: TextStyle(
                    color: Colors.black, fontWeight: FontWeight.w600)),
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: TextButton(
            style: TextButton.styleFrom(
              backgroundColor: const Color(0xFF3482ff),
              padding: const EdgeInsets.symmetric(vertical: 14),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16)),
            ),
            onPressed: _onConfirm,
            child: Text(l10n.confirm,
                style: TextStyle(
                    color: Colors.white, fontWeight: FontWeight.w600)),
          ),
        ),
      ],
    );
  }
}
